/*
 * Commandline functions
 */
var cmd_sentTime;
var cmd_tab;
var cmd_content;
var cmd_output;
var cmd_command;
var cmd_history = new Array();
var cmd_historyIndex = -1;

function cmd_onKeyPress(event) {
	var code = event.keyCode;
	switch (code) {
	case 9:
		break;
	case 13:
		cmd_send();
		break;
	case 38:
		cmd_displayHistory(1);
		break;
	case 40:
		cmd_displayHistory(-1);
		break;
	default:
		return true;
	}
	return false;
}

function cmd_displayHistory(_plus) {
	var index=cmd_historyIndex+_plus
	if (index >= 0 && index < cmd_history.length) {
		cmd_command.value = cmd_history[index];
		cmd_historyIndex=index;
	} else {
		if (index < 0) {
			cmd_historyIndex=-1;
			cmd_command.value = "";
		}
	}
}

function cmd_init() {
	cmd_content = document.getElementById("cmd_content");
	cmd_tab = main_createTab("cmd_content", _T("Command"));
	main_contents.push(cmd_content);
	var note = document.createElement("p");
	note.style.fontStyle = "italic";
	note.innerHTML = _T("CmdNote");
	cmd_output = document.createElement("div");
	cmd_command = document.createElement("input");
	cmd_command.setAttribute("class", "cmd_command");
	cmd_command.onkeypress = cmd_onKeyPress;
	var label = document.createElement("div");
	label.innerHTML = _T("Command");
	cmd_content.appendChild(note);
	cmd_content.appendChild(label);
	cmd_content.appendChild(cmd_command);
	cmd_content.appendChild(cmd_output);
}

function cmd_send() {
	cmd_command.disabled = true;
	var value = cmd_command.value;
	if (cmd_history[0] != value) {
		cmd_history.unshift(value);
	}
	cmd_historyIndex = -1;
	cmd_command.value = _T("WaitDots");
	var req = new XMLHttpRequest();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			cmd_command.disabled = false;
			cmd_command.value = "";
			addPing(new Date().getTime() - cmd_sentTime);
			if (req.status == 200) {
				var response=main_readJSONResponse(req);
				if(!response){
					return;
				}
				cmd_output.innerHTML = "<pre>" + response.output + "</pre>";
			}
		}
	};
	var re=/[ ]+/;
	var cmdArray = value.split(re);
	main_encryptReq(req,"command",cmdArray);
	cmd_sentTime = new Date().getTime();
}
